#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Farmer Li, 公众号: 很酷的程序员/RealCoolEngineer
# @Date: 2021-12-25
# @Question: https://www.zhihu.com/question/508218242/answer/2285462542

from pathlib import Path
import shutil

import click

# 类别关键字， 顺序匹配，如果同时包含GB和TR，会复制到这两个类别下
CATEGORIES = ['GB', 'TR']


def organize_files_by_name(folder: Path, organized_forder: Path,
                           categories: list):
    """通过文件名包含不同的字符串进行分类整理

    Parameters
    ----------
    folder : Path
        源目录，需要整理的目录，不递归处理
    organized_forder : Path
        目标目录，整理之后的文件保存目录
    """
    # 创建分类目录
    (organized_forder / 'Others').mkdir(parents=True, exist_ok=True)
    for t in CATEGORIES:
        (organized_forder / t).mkdir(parents=True, exist_ok=True)

    # 遍历文件
    for f in folder.iterdir():
        if not f.is_file():
            # 跳过目录
            continue
        matched = False
        for t in CATEGORIES:
            # 如果文件名包含某个关键字，复制到目标分类目录
            if t in f.stem:
                matched = True
                shutil.copy(f, organized_forder / t)
                # 如果只想归类到最先满足的类别，在这里提前退出即可
                # break
        if not matched:
            # 如果不包含任何关键字，归类到Others类别
            shutil.copy(f, organized_forder / 'Others')


@click.command()
@click.argument('src-dir', type=Path)
@click.argument('dst-dir', type=Path)
@click.option('-c',
              '--category',
              'categories',
              multiple=True,
              default=CATEGORIES)
def main(src_dir: Path, dst_dir: Path, categories):
    organize_files_by_name(src_dir, dst_dir, categories)


if __name__ == '__main__':
    main()
